package yc.web.filter;

import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;
import redis.clients.jedis.Jedis;
import yc.bean.User;
import yc.dao.RedisHelper;
import yc.utils.YcConstants;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;

@WebFilter(filterName = "DeviceFilter",value = "/user.action")
public class DeviceFilter extends CommonFilter{
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        chain.doFilter(req,resp);
        //只针对 login操作 的响应上做处理，判断 是否登录成功
        HttpServletRequest request=(HttpServletRequest) req;
        String op=request.getParameter("op");
        if ("login".equals(op)){
            //说明是login操作
            //如果登录成功 在session中一定有user 一个 attribute
            HttpSession session=request.getSession();
            if (session.getAttribute(YcConstants.REUSER)!=null){
                User user=(User) session.getAttribute(YcConstants.REUSER);
                String uid=user.getUserid()+"";
                //取出request中记录的所有的设备信息
                //redis -> 键的设计 +值的类型
                //safari Set<用户id>
                //chrome
                //ie
                //firefox
                //
                //用户id_device List<设备名>
                Browser browser= UserAgent.parseUserAgentString(request.getHeader("User-Agent")).getBrowser();
                String browserName=browser.getName();
                Jedis jedis= RedisHelper.getRedisInstance();
                jedis.sadd(browserName+YcConstants.REDIS_DEVICE_USERS,uid);
                jedis.lpush(uid+YcConstants.REDIS_USER_DEVICE,browserName);
                jedis.close();
            }
        }
    }
}
